import 'package:bili_caricature/models/handle_state.dart';
import 'package:bloc/bloc.dart';
import '../../../base/base_state.dart';
import '../../../models/response_model.dart';
import '../../../net/http_config.dart';
import '../../../net/ltt_https.dart';
import '../../../widgets/easy_loading.dart';
import '../../bloc/model/cartoon_model.dart';
import '../model/banner_model.dart';
import 'event.dart';
import 'state.dart';

class BlocStaggeredGridViewBloc extends Bloc<BiliBookShelfEvent, StaggeredGridViewState> {
  BlocStaggeredGridViewBloc() : super(StaggeredGridViewState().init()) {
    on<GetListDataEvent>(_getDataEvent);
    on<GetBannerDataEvent>(_getBannerDataEvent);
  }

  /// 获取数据
  Future<void> _getDataEvent(event, emit) async {
    XsEasyLoading.showLoading();

    if (event.url == '') {
      XsEasyLoading.dismiss();

      /// 没有更多数据了
      state.isNoMoreDataState = true;
      state.netState = NetState.dataSuccessState;
      emit(state.clone());
      return;
    }
    ResponseModel? responseModel =
        await LttHttp().request<CarDataModel>(event.url, method: HttpConfig.get);
    XsEasyLoading.dismiss();
    int number = event.pageNum;
    state.isNoMoreDataState = false;

    /// 处理状态
    state.netState = HandleState.handle(responseModel, state,successCode: 0);
    if (state.netState == NetState.dataSuccessState) {
      CarDataModel carDataModel = responseModel.data;
      if (number == 1) {
        state.dataList = handleData(carDataModel.feeds ?? []);
        if ((state.dataList ?? []).isEmpty) {
          state.netState = NetState.emptyDataState;
        }
      } else {
        state.dataList?.addAll(carDataModel.feeds ?? []);
        state.dataList = handleData(state.dataList ?? []);
      }
    }
    emit(state.clone());
  }

  /// 处理数据
  List handleData(List list) {
    for (int i = 0; i < list.length; i++) {
      CartoonModel cartoonModel = list[i];
      if (i % 3 == 0) {
        cartoonModel.crossAxisCount = 2;
      } else {
        cartoonModel.crossAxisCount = 1;
      }
    }
    return list;
  }

  ///
  /// 获取轮播图数据
  Future<void> _getBannerDataEvent(event, emit) async {
    ResponseModel? responseModel =
        await LttHttp().request<List<BannerModel>>(event.bannerUrl, method: HttpConfig.get);
    state.bannerList = responseModel.data;
    state.netState = NetState.dataSuccessState;
    emit(state.clone());
  }
}
